package cn.whx.hrm.service.impl;

import cn.whx.hrm.constatan.RegistConstant;
import cn.whx.hrm.domain.VipUser;
import cn.whx.hrm.dto.SmsDto;
import cn.whx.hrm.mapper.VipUserMapper;
import cn.whx.hrm.service.IVerifyCodeService;
import cn.whx.hrm.util.AjaxResult;
import cn.whx.hrm.util.ValidUtils;
import cn.whx.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Service
public class IVerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VipUserMapper vipUserMapper;
    @Override
    public AjaxResult imageCode(String key) throws IOException {
        //校验key
        ValidUtils.assertNotNull(key,"key值不能为空");
        //验证码转换成base64的格式
        BASE64Encoder encoder = new BASE64Encoder();
        String code = VerifyCodeUtils.generateVerifyCode(4).toLowerCase();
        //code存入redis里
        redisTemplate.opsForValue().set(key, code, 1L, TimeUnit.MINUTES);
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(100, 40, data, code);
        String encode = encoder.encode(data.toByteArray());
        return AjaxResult.me().setResultObj(encode);


    }

    @Override
    public AjaxResult sendSmsCode(@Valid SmsDto smsDto) {
        //校验参数交给303管理
        VipUser vipUser = new VipUser();
        vipUser.setPhone(smsDto.getMobile());
        //校验手机是否注册过了
        VipUser user = vipUserMapper.selectOne(vipUser);
        if (user!=null){
            throw  new RuntimeException("这个手机号已经注册过了");
        }
        //没注册过的话redis里的图片验证码和用户的注册验证码进行比较
        String codeKey = smsDto.getImageCodeKey();
        Object obj = redisTemplate.opsForValue().get(codeKey);
        ValidUtils.assertNotNull(obj,"图片验证码已经失效了");
        String imgCode = obj.toString();
        //获取用户输入的图片验证码
        String userImgCode = smsDto.getImageCode().toLowerCase().trim();
        if (!userImgCode.equals(imgCode)){
            throw new RuntimeException("图片验证码输入错误");
        }
        //校验成功发送手机验证码，保存到redis里
        String code = VerifyCodeUtils.generateVerifyCode(4, "1234567890");
        //发送验证码
        System.out.println(code);
        //将验证码存入redis中  设置过期时间
        String key = RegistConstant.REGIST_KEY + "::" + smsDto.getMobile()             ;
        redisTemplate.opsForValue().set(key, code,1L,TimeUnit.MINUTES);
        return AjaxResult.me();
    }
}